package com.zlc.sykks.interceptor;


import cn.hutool.json.JSONUtil;
import com.zlc.sykks.entity.UserDTO;
import com.zlc.sykks.utils.UserHodler;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.concurrent.TimeUnit;

import static com.zlc.sykks.constance.UserConstance.USER_LOGIN_TOKEN_PREFIX;
import static com.zlc.sykks.constance.UserConstance.USER_LOGIN_TOKEN_TTL;

/*
*   刷新toekn拦截器
* */
@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.获取token
        String token = request.getHeader("authorization");
        log.info("jwt校验:{}", token);
        //2.如果token为空
        if(StringUtils.isBlank(token)){
            return true;
        }

        //3.判断token是否能正确查询信息
        String k = USER_LOGIN_TOKEN_PREFIX + ":" + token;
        String v = stringRedisTemplate.opsForValue().get(k);
        if(StringUtils.isBlank(v)){
            return true;
        }

        //4.根据token 生成userDTO
        UserDTO userDTO = JSONUtil.toBean(v, UserDTO.class);
        userDTO.setToken(token);

        //5.保存到ThreadLocal
        UserHodler.saveUser(userDTO);

        //6.刷新toekn的有效期
        stringRedisTemplate.expire(k,USER_LOGIN_TOKEN_TTL, TimeUnit.SECONDS);

        //7.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        UserHodler.removeUser();
    }


}
